package com.xjm.mid.compent.rabbitmq.config;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author jaymin
 */
@Configuration
@Slf4j
public class RabbitMQDelayConfig {

    /**
     * 延迟队列，把消息放在这里会自动过期
     */
    public static final String DELAY_QUEUE = "jay.delay.queue";

    /**
     * 延迟队列交换机
     */
    public static final String DELAY_EXCHANGE = "jay.delay.exchange";

    /**
     * 延迟队列路由
     */
    public static final String DELAY_ROUTINGKEY = "jay.delay.routingKey";

    /**
     * 死信队列
     */
    public static final String DEAD_LETTER_QUEUE = "jay.dlx.queue";

    /**
     * 死信交换机
     */
    private static final String DEAD_LETTER_EXCHANGE = "jay.dlx.exchange";

    /**
     * 死信队列路由
     */
    private final String DEAD_LETTER_ROUTINGKEY = "jay.dlx.routingKey";



    @Bean
    public RabbitTemplate rabbitTemplate(CachingConnectionFactory connectionFactory) {
        connectionFactory.setPublisherConfirmType(CachingConnectionFactory.ConfirmType.CORRELATED);
        connectionFactory.setPublisherReturns(true);
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        // 当交换机无法正确投递消息的时候，RabbitMQ会调用Basic.Return命令将消息返回给生产者
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> log.info("消息发送成功:correlationData({}),ack({}),cause({})", correlationData, ack, cause));
//        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> log.info("消息丢失:exchange({}),route({}),replyCode({}),replyText({}),message:{}", exchange, routingKey, replyCode, replyText, message));
        return rabbitTemplate;
    }

    /**
     *
     * @return FanoutExchange
     */
    @Bean
    public FanoutExchange delayExchange() {
        return new FanoutExchange(DELAY_EXCHANGE);
    }


    /**
     * 延迟队列配置
     * <p>
     * 1、params.put("x-message-ttl", 5 * 1000);
     * 第一种方式是直接设置 Queue 延迟时间 但如果直接给队列设置过期时间,这种做法不是很灵活,（当然二者是兼容的,默认是时间小的优先）
     * 2、rabbitTemplate.convertAndSend(book, message -> {
     * message.getMessageProperties().setExpiration(2 * 1000 + "");
     * return message;
     * });
     * 第二种就是每次发送消息动态设置延迟时间,这样我们可以灵活控制
     **/
    @Bean
    public Queue delayQueue() {
        Map<String, Object> args = new HashMap<>();
        // x-dead-letter-exchange 声明了队列里的死信转发到的DLX名称，
        args.put("x-dead-letter-exchange", DEAD_LETTER_EXCHANGE);
        // x-dead-letter-routing-key 声明了这些死信在转发时携带的 routing-key 名称。
        args.put("x-dead-letter-routing-key", DEAD_LETTER_ROUTINGKEY);
        return new Queue(DELAY_QUEUE, true, false, false, args);
    }

    @Bean
    public Binding delayBinding() {
        return BindingBuilder.bind(delayQueue()).to(delayExchange());
    }


    @Bean
    public Queue dlxQueue() {
        return new Queue(DEAD_LETTER_QUEUE, true);
    }

    /**
     *
     **/
    @Bean
    public DirectExchange dlxExchange() {
        return new DirectExchange(DEAD_LETTER_EXCHANGE);
    }

    @Bean
    public Binding dlxBinding() {
        return BindingBuilder.bind(dlxQueue()).to(dlxExchange()).with(DEAD_LETTER_ROUTINGKEY);
    }


}
